Variables and Operators in Swift
Posted on 13 May, 2018 in Swift
Hello there,
In this part of Swift lecture, we will touch at variables and operators. So let's get down with the business.
Variables
Let's look at the following code.
let itIsTen : Int = 10
var thisIsAlsoTen : Int = 10
We have 2 different type of variables. The 'let' one is constant. Therefore we would get an error if we do the following code. However, we should always use let if it is possible.
// We get following error
// error: cannot assign to value: 'constantTen' is a 'let' constant
let constantTen : Int = 10
constantTen = 5
// Perfectly fine
var notConstantTen : Int = 10
notConstantTen = 5
Swift is type safe. That means boolean stays boolean, integer stays integer. Hence, we use let/var variableName : variableType = value formula for defining a variable.
var notConstantInt : Int = 10
var notConstantBool : Bool = true
var notConstantDouble : Double = 3.14
var notConstantString : String = "Hello There, General Kenobi"
In Swift, we can assign nil to a variable. It means it has nothing. Do not confuse with zero. It is an integer. However nil means empty. We just need to add ? to variable type.
var canBeNilInt : Int? = nil
var canNotBeNilInt : Int = nil // This line gets an error
// We can unbox the ? with using if statement
if canBeNilInt != nil {
// Go ahead. Now we are sure that canBeNilInt is not nil.
}
Swift is smart enough to assume the variable type. So, typing the variable type is not mandatory.
// Perfectly okay assignments
var notConstantInt = 10
var notConstantBool = true
var notConstantDouble = 3.14
var notConstantString = "Hello There, General Kenobi"
Operators
As with the other programming languages, we do have many operators to use in Swift.
let constantEleven = 10 + 1
let constantNine = 10 - 1
let constantTwenty = 10 * 2
var notConstantFive = 10 / 2
var minusEleven = -constantEleven
var notTrue = !true
var bestSentenceEver = "Hello there, " + " General Kenobi"
var reminderOfFive = 5 % 2
var notEqual = 5 != 5 // Returns false
var Equal = 5 == 5
var biggerEqual = 5 >= 5
var smallerEqual = 5 <= 5
let nullInt : Int? = nil
let fiveOrTen = (nullInt == nil ? 5 : 10) // Since nullInt is nil, it returns 5.